// pages/authorizedLogin/authorizedLogin.js
const app = getApp();
var config = require('../../config.js');
var host = app.globalData.host;
var util = require('../../utils/util.js');
var WXBizDataCrypt = require('../../utils/cryptojs/RdWXBizDataCrypt.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    status:0
  },

  onGetUserInfo: function (e) {
  var that = this;
  wx.login({
    success: function(res) {
      if(res.code){
        that.getOpenId(res.code);
      }
    },
    
  })

    var appId = 'wx98135d6b754b102d'
    
    // var encryptedData = e.detail.encryptedData;
    // var iv = e.detail.iv;
    // console.info(sessionKey);
    // var pc = new WXBizDataCrypt(appId, sessionKey);
    // var data = pc.decryptData(encryptedData, iv);
    // console.log('解密后 data: ', data)
    
  },
  getOpenId: function (code) {
    var _this = this
    wx.request({
      url: config.openUserIdUrl,
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        "code": code,
        "tenantCode": config.tenantCode,
      },
      success: function (result) {
        console.log("userResult:"+result);
        wx.setStorageSync("sessionKey", result.data.session_key);
        var sessionKey = wx.getStorageSync("sessionKey")
        if (sessionKey != "") {
          _this.setData({
            status: 1
          })
        }
      },
    })
  },
  getPhoneNumber: function (e) {
    var that = this;
    var sessionKey = wx.getStorageSync("sessionKey");
    var abc=e.detail;
    console.log("E:"+e.detail);
    var encryptedData = e.detail.encryptedData;
    var iv = e.detail.iv;
    var appId = 'wx6911c6c58a99d548'
    var pc = new WXBizDataCrypt(appId, sessionKey);
    var data = pc.decryptData(encryptedData, iv);
    wx.setStorageSync("phoneNumber", data.phoneNumber);
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      
      var userPhone = wx.getStorageSync("phoneNumber");
      var that = this;
      if (userPhone == "" || userPhone == null || userPhone == undefined) {
        app.tip("授权之后才可以登录", "none");
        return false;
      }
      console.info(userPhone)
  
      that.doLogin(e);
   


      
    }
  },
  	/**
	 * 登录
	 */
  doLogin: function (e) {
    var userName =wx.getStorageSync("phoneNumber");
    var unionId ="";
    if (userName == null || userName.length == 0) {
      app.tip('用户名不能为空', 'loading')
      return false;
    }
  
    var name="";
    //userPass = utilMd5.hexMD5(userPass);

    
    var city="";
    var province="";
    var address="";
   if(app.currentPosition!=null&&app.currentPosition!=undefined){
     city=app.currentPosition.address_component.city;
     province=app.currentPosition.address_component.province;
     address=app.currentPosition.address;
   }
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.request({
      url: config.loginAutoUrl,
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        "username": userName,
        "unionId": unionId,
        "name": name,
        "openid": app.openid,
        "address": address,
        "city": city,
        "province": province,
        "code": config.tenantCode,
      },
      success: function (result) {
        wx.hideLoading();
        var data = result.data;
        if (data && data.code && data.code == 100) {
          var content = data.content;
          app.setLoginUser(data.content)
          //wx.switchTab({ url: '../index/index' })
          wx.reLaunch({
            url: '../index/index',
          })
        } else {
          var errMsg;
          if (data && data.msg) {
            errMsg = data.msg
          } else {
            errMsg = result.statusCode + ":" + result.errMsg
          }
          app.tip(errMsg, 'none')
        }
      },
      fail: function ({ errMsg }) {
        wx.hideLoading()
        app.tip(errMsg, 'none')
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})


//省选择器的数据加载
function getProvinceList(that) {
  wx.showLoading({
    title: '加载中'
  })
  wx.request({
    url: config.requestUrl + "administrativeDivision/getProvinceList",
    method: "POST",
    header: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    success: function (res) {
      wx.hideLoading()

      var data = res.data;
      if (data && data.code && data.code == 100) {
        var provinceLists = data.content;
        //console.log(provinceLists)
        //console.log(app.currentPosition);
        if (app.currentPosition == null) {
          that.setData({ provinceList: provinceLists, province: provinceLists[0].administrativeDivisionName })
          getCityList(provinceLists[0].administrativeDivisionId, that);
        } else {
          var provinceId = "";
          for (var i = 0; i < provinceLists.length; i++) {
            if (app.currentPosition.ad_info.province == provinceLists[i].administrativeDivisionName) {
              provinceId = provinceLists[i].administrativeDivisionId;
            }
          }
          that.setData({ provinceList: provinceLists, province: app.currentPosition.ad_info.province })
          getCityList(provinceId, that);
        }
      } else {
        var errMsg;
        if (data && data.msg) {
          errMsg = data.msg
        } else {
          errMsg = res.statusCode + ":" + res.errMsg
        }
        app.tip(errMsg, 'none')
      }
    },
    fail: function ({ errMsg }) {
      wx.hideLoading()
      app.tip(errMsg, 'none')
    }
  })
}
